package com.jzl.util;

import java.util.Collection;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executor;

public class ExecutorUtils
{
    public static void multThreadCountdown(Executor executor, Collection<? extends Runnable> runnables)
    {
        if (runnables == null || runnables.isEmpty())
        {
            return;
        }
        final CountDownLatch ready = new CountDownLatch(runnables.size());
        final CountDownLatch start = new CountDownLatch(1);
        final CountDownLatch done = new CountDownLatch(runnables.size());
        runnables
                .parallelStream()
                .map(runnable -> (Runnable) () ->
                {
                    ready.countDown();
                    try
                    {
                        start.await();
                        runnable.run();
                    } catch (Exception e)
                    {
                        e.printStackTrace();
                    } finally
                    {
                        done.countDown();
                    }
                }).forEach(executor::execute);

        try
        {
            ready.await();
            start.countDown();
            done.await();
        } catch (InterruptedException e)
        {
            e.printStackTrace();
        }
    }
}
